#include "u8g2Helper.h"

void u8g2EaseInit(U8g2EaseMoveHandler *handler, int accel, int maxSpeed, int currentValue, int targetValue)
{
    handler->accel = accel;
    handler->maxSpeed = maxSpeed;
    handler->currentValue = currentValue;
    handler->targetValue = targetValue;

    handler->__currentPos = currentValue;
    handler->__currentSpeed = 0;

    // 计算加速度起始点和结束点的位置
    handler->__accFrom1ToMaxSpeedValuePosition = (maxSpeed * maxSpeed) / (2 * accel);
    handler->__accFromMaxSpeedTo1ValuePosition = targetValue - handler->__accFrom1ToMaxSpeedValuePosition;
}

int u8g2Ease(U8g2EaseMoveHandler *handler)
{
    if (handler->__currentPos < handler->__accFrom1ToMaxSpeedValuePosition)
    {
        // 缓入阶段
        handler->__currentSpeed += handler->accel;

        // 边界处理，确保加速度不超过最大值
        if (handler->__currentSpeed > handler->maxSpeed)
        {
            handler->__currentSpeed = handler->maxSpeed;
        }
    }
    else if (handler->__currentPos >= handler->__accFromMaxSpeedTo1ValuePosition)
    {
        // 缓出阶段
        handler->__currentSpeed -= handler->accel;

        // 边界处理，确保加速度不小于1
        if (handler->__currentSpeed < 1)
        {
            handler->__currentSpeed = 1;
        }
    }
    else
    {
        // 匀速阶段
        handler->__currentSpeed = handler->maxSpeed;
    }

    // 更新位置
    handler->__currentPos += handler->__currentSpeed;

    // 边界处理，确保位置不超过目标值
    if (handler->__currentPos > handler->targetValue)
    {
        handler->__currentPos = handler->targetValue;
    }

    return handler->__currentPos;
}
